<script setup>
import SvgIcon from '@/components/SvgIcon/SvgIcon.vue'
import useAppStore from '@/store/modules/app.js'

const appStore = useAppStore()

function toggleColorScheme(event) {
  const { startViewTransition } = useViewTransition(() => {
    appStore.colorScheme && appStore.setColorScheme(appStore.colorScheme === 'dark' ? 'light' : 'dark')
  })
  startViewTransition()?.ready.then(() => {
    const x = event.clientX
    const y = event.clientY
    const endRadius = Math.hypot(
      Math.max(x, innerWidth - x),
      Math.max(y, innerHeight - y),
    )
    const clipPath = [
      `circle(0px at ${x}px ${y}px)`,
      `circle(${endRadius}px at ${x}px ${y}px)`,
    ]
    document.documentElement.animate(
      {
        clipPath: appStore.colorScheme !== 'dark' ? clipPath : clipPath.reverse(),
      },
      {
        duration: 300,
        easing: 'ease-out',
        pseudoElement: appStore.colorScheme !== 'dark' ? '::view-transition-new(root)' : '::view-transition-old(root)',
      },
    )
  })
}

function useViewTransition(callback) {
  function startViewTransition() {
    if (!document.startViewTransition || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      callback()
      return
    }
    return document.startViewTransition(async () => {
      await callback()
    })
  }

  return {
    startViewTransition,
  }
}
</script>

<template>
  <SvgIcon
    class="text-xl cursor-pointer"
    :name="{
      '': 'codicon:color-mode',
      'light': 'ri:sun-line',
      'dark': 'ri:moon-line',
    }[appStore.colorScheme]"
    @click="toggleColorScheme"
  />
</template>

<style lang="scss" scoped>

</style>
